<template>
  <div class="ride-sharing-app">
    <main class="ride-list-container">
      <article class="ride-card">
        <div class="ride-details">
          <div class="time-location-group">
            <div class="time-stamps">
              <time>{{ formattedStartTime }}</time>
              <time>{{ formattedEndTime }}</time>
            </div>
            <img
              src="https://cdn.builder.io/api/v1/image/assets/TEMP/c43e78adf3cb5a1acbec30bd52aa65dd2da672a48dc1e3a212b18baacc8c9e47?placeholderIfAbsent=true&apiKey=933e78dc5ac54c44868b43c2dcd912d5"
              alt="Route indicator"
              class="route-indicator"
            />
            <div class="location-details">
              <div class="pickup-point">
                <h2 class="location-name">{{ pinInfo.startPoint }}</h2>
                <div class="passenger-indicators">
                  <img
                    v-for="(n, index) in pinInfo.joinedPassengers"
                    :key="'occupied-' + index"
                    src="https://cdn.builder.io/api/v1/image/assets/TEMP/8f13ed4ce31aca070cc8d74d17dd6bf8c5c315113ea78c8271f504c4b2925326?placeholderIfAbsent=true&apiKey=933e78dc5ac54c44868b43c2dcd912d5"
                    alt="Occupied seat indicator"
                    class="passenger-icon"
                  />
                  <img
                    v-for="(n, index) in (pinInfo.totalPassengers - pinInfo.joinedPassengers)"
                    :key="'vacant-' + index"
                    src="https://cdn.builder.io/api/v1/image/assets/TEMP/6000bf3a45354cca61c730438a13d1c138d4c1b266c43d868217bcca59a04424?placeholderIfAbsent=true&apiKey=933e78dc5ac54c44868b43c2dcd912d5"
                    alt="Vacant seat indicator"
                    class="passenger-icon"
                  />
                </div>
              </div>
              <h2 class="location-name">{{ pinInfo.endPoint }}</h2>
            </div>
          </div>
        </div>
        <div class="driver-action-group">
          <div class="driver-info">
            <img
              src="https://cdn.builder.io/api/v1/image/assets/TEMP/7c39c3bb9015cbb7888b2cf634549fa4731446fbbcec83a3cb8d8f6bd5415ce4?placeholderIfAbsent=true&apiKey=a8197e2c79ff4f54b36ec1cb4eb509e7"
              alt="Driver profile"
              class="driver-photo"
            />
            <div class="driver-details">
              <span class="driver-name">{{ pinInfo.leaderName }}</span>
              <!-- 信用评级展示 -->
              <span class="rating-box" :class="ratingClass">{{ ratingText }}</span>
              <span class="time-ago">{{ publishTime }}</span>
            </div>
          </div>
          <!-- 添加按钮 -->
          <button v-if="plusButton" :class="['add-button',addButtonStyle]" @click="onAddButtonClick">+</button>
        </div>
      </article>
    </main>
  </div>
</template>


<script>
import { PinlistAPI,UserAPI ,getUserInfo,ChatAPI} from '../services/api'; // 引入 PinlistAPI
import { fetchPinInfo } from '../services/pin'; // 引入 fetchPinInfo
export default {
  props: {
    pinID: {
      type: Number,
      required: true,
    },
    startTime: {
      type: String,
      required: false,
    },
    endTime: {
      type: String,
      required: false,
    },
    startPoint: {
      type: String,
      required: false, // 可选，可能会从 API 中获取覆盖值
    },
    endPoint: {
      type: String,
      required: false, // 可选，可能会从 API 中获取覆盖值
    },
    userName: {
      type: String,
      required: false, // 如果从 API 加载，设置为可选
    },
    publishTime: {
      type: String,
      required: false,
    },
    joinedPassengers: {
      type: Number,
      required: false,
      default: 0,
    },
    totalPassengers: {
      type: Number,
      required: false,
    },
    userCreditScore: {
      type: Number,
      required: false, // 可选，优先从 API 中获取
    },
	userID: {
	  type: Number,
	  required: false, // 可选，优先从 API 中获取
	},
	plusButton: {
	  type: Boolean,
	  required: false, // 可选，优先从 API 中获取
	},
  },
  data() {
    return {
      pinInfo: null, // 存储拼车信息
	  isJoinStyle: true,
    };
  },
  computed: {
	addButtonStyle() {
	  return this.isJoinStyle ? 'join' : 'quit';
	},
    formattedStartTime() {
      return this.formatTime(this.pinInfo.departureTime);
    },
    formattedEndTime() {
      return this.formatTime(this.pinInfo.arrivalTime);
    },
    // 信用评分对应的评级文本
    ratingText() {
		return "GO分  "+this.pinInfo.creditRating;
    },
    // 信用评分对应的样式类
    ratingClass() {
      if (this.pinInfo.creditRating > 90) {
        return "rating-excellent";
      } else if (this.pinInfo.creditRating > 60) {
        return "rating-good";
      } else {
        return "rating-average";
      }
    },
  },
  async created() {
    // 在组件加载时运行逻辑
	console.log("NOW:",this.pinID);
	console.log(this.startTime);
    this.pinInfo= await fetchPinInfo(this.pinID);
	let members = [];
	try {
		members = JSON.parse(this.pinInfo.members);  // 将 members 解析为数组
	} catch (e) {
		console.error('Failed to parse members:', e);
	}
	// 检查用户是否在 members 中
	if (this.userID) {
	// 检查 userID 是否在成员列表中
		this.isJoinStyle = !members.some(member => member == this.userID);
	}
	console.log("EEEE",this.pinInfo);
  },
  methods: {
    formatTime(timeString) {
      const date = new Date(timeString);
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      return `${hours}:${minutes}`;
    },
	
	async onAddButtonClick() {
		   uni.vibrateShort();
		   console.log(this.pinInfo.members);
		   console.log(this.isJoinStyle);
		   if (this.isJoinStyle){
				const userID = this.userID;
				const pinID = this.pinID;
				const pinInfo = this.pinInfo;
				console.log(pinInfo.members);
				console.log(pinInfo.leader);
				console.log(pinInfo);
				// 调用已经实现的添加成员接口
				const response = await PinlistAPI.addMember(pinID, userID);
				console.log(response.message);
				switch (response.message) {
					case 'User added to members successfully':
						uni.showToast({
							title: '成员添加成功',
							icon: 'success'
						});
						// 此处可添加业务逻辑，比如刷新页面显示成员列表等
						this.isJoinStyle = !this.isJoinStyle;
						const userInfo=await getUserInfo();
						const chatData = {
						  pinID: this.pinID,
						  userID: this.userID, // 当前用户ID，需要动态获取
						  messageContent: `用户${userInfo.username}已加入拼单！`,
						};
						ChatAPI.createChat(chatData)
						  .then((response) => {
						    console.log("Message sent successfully:", response);
						  })
						  .catch((error) => {
						    console.error("Failed to send message:", error);
						  });
						break;
					case 'Pinlist not found':
						uni.showToast({
							title: '未找到对应的Pinlist，请检查',
							icon: 'none'
						});
						break;
					case 'User is the leader and cannot be added to members':
						uni.showToast({
							title: '你已经是负责人，不能添加到成员中',
							icon: 'none'
						});
						break;
					case 'User is already in members':
						uni.showToast({
							title: '你已经加入了',
							icon: 'none'
						});
						break;
					case 'Exceeding the total number of passengers limit':
						uni.showToast({
							title: '该拼单已满员',
							icon: 'none'
						});
						break;
					default:
						uni.showToast({
							title: '操作出现未知错误，请稍后再试',
							icon: 'none'
						});
						break;
				}
			}else
			{
			        // 删除成员操作
			        const userID = this.userID;
			        const pinID = this.pinID;
			
			        const response = await PinlistAPI.removeMember(pinID, userID);
			        console.log(response.message);
			
			        switch (response.message) {
			            case 'User removed from members successfully':
			                uni.showToast({
			                    title: '您已成功退出拼单',
			                    icon: 'success'
			                });
							const userInfo=await getUserInfo();
							const chatData = {
							  pinID: this.pinID,
							  userID: this.userID, // 当前用户ID，需要动态获取
							  messageContent: `用户${userInfo.username}已退出拼单！`,
							};
							ChatAPI.createChat(chatData)
							  .then((response) => {
							    console.log("Message sent successfully:", response);
							  })
							  .catch((error) => {
							    console.error("Failed to send message:", error);
							  });
			                this.isJoinStyle = !this.isJoinStyle;// 切换样式，刷新页面等
			                break;
			            case 'Pinlist not found':
			                uni.showToast({
			                    title: '未找到对应的Pinlist，请检查',
			                    icon: 'none'
			                });
			                break;
			            case 'User not in members':
			                uni.showToast({
			                    title: '该用户不在成员列表中',
			                    icon: 'none'
			                });
			                break;
			            case 'Leader cannot be removed from members':
			                uni.showToast({
			                    title: '负责人不能从成员中删除',
			                    icon: 'none'
			                });
			                break;
			            default:
			                uni.showToast({
			                    title: '操作出现未知错误，请稍后再试',
			                    icon: 'none'
			                });
			                break;
			        }
					}
	}
  },
};
</script>


<style scoped>
.ride-sharing-app {
  background: #fff;
  max-width: 480px;
  width: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.status-bar {
  background: #fff;
  min-height: 50px;
  padding-top: 21px;
}

.status-bar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.time-display {
  color: #000;
  font: 590 17px/1 SF Pro, sans-serif;
  flex: 1;
  text-align: center;
  padding: 0 6px 0 16px;
}

.dynamic-island {
  width: 124px;
  height: 10px;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 7px;
  justify-content: center;
  flex: 1;
  padding: 0 16px 0 6px;
}

.status-icon {
  width: auto;
  height: 17px;
  object-fit: contain;
}

.ride-list-container {
  padding: 0px 4px;
  box-shadow: none;
}

.ride-card {
  background: #fff;
  border-radius: 25px;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.25);
  padding: 15px;
  margin-bottom: 5px;
  margin-top: 5px;
  width: 100%;  /* 占满父容器宽度 */
  max-width: 450px; /* 限制最大宽度 */
  box-sizing: border-box; /* 包括padding和border */
}


.time-location-group {
  display: flex;
  gap: 10px;
}

.time-stamps {
  color: #303030;
  font: 500 14px Poppins, sans-serif;
  width: 64px;
  display: flex;
  flex-direction: column;
  gap: 35px;
}

.route-indicator {
  width: 10px;
  height: auto;
}

.location-details {
  flex: 1;
  text-align: right;
}

.pickup-point {
  margin-bottom: 8px;
}

.location-name {
  color: #303030;
  font: 400 14px PingFang SC, sans-serif;
  margin: 0;
}

.passenger-indicators {
  display: flex;
  gap: 4px;
  margin-top: 4px;
}

.passenger-icon {
  width: 12px;
  height: 12px;
}

.driver-info {
  display: flex;
  gap: 15px;
  margin-top: 21px;
}

.driver-photo {
  width: 42px;
  height: 42px;
}

.driver-details {
  display: flex;
  flex-direction: column;
}

.driver-name {
  color: #000;
  font: 500 14px Poppins, sans-serif;
}

.time-ago {
  color: #8c8c8c;
  font: 400 12px Poppins, sans-serif;
}

.navigation-bar {
  position: relative;
  margin-top: auto;
}

.home-indicator-container {
  border-top: 0 solid rgba(0, 0, 0, 0.3);
  background: rgba(255, 255, 255, 0.75);
  display: flex;
  justify-content: center;
  padding: 8px 0;
}

.home-indicator {
  background: #000;
  border-radius: 100px;
  width: 144px;
  height: 5px;
}

.action-button {
  background: #000;
  border-radius: 25px 25px 0 0;
  position: absolute;
  top: -51px;
  right: 0;
  left: 0;
  height: 51px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.action-icon {
  width: 24px;
  height: 24px;
}

.tab-navigation {
  position: absolute;
  top: 7px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
}

.tab-button {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 8px 40px;
  background: none;
  border: none;
  cursor: pointer;
}

.tab-icon {
  width: 25px;
  height: 25px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  border: 0;
}
/* 信用评级的样式 */
.rating-box {
  display: inline-block;
  margin-top: 3px;
  padding: 2px 4px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: bold;
  text-align: center;
  color: #fff;
}

/* 信用优秀（绿色） */
.rating-excellent {
  background-color: #4caf50; /* 绿色 */
}

/* 信用良好（黄色） */
.rating-good {
  background-color: #ffc107; /* 黄色 */
}

/* 信用一般（红色） */
.rating-average {
  background-color: #f44336; /* 红色 */
}
.driver-action-group {
  display: flex; /* 启用 Flex 布局 */
  flex-direction: row;
  align-items: center; /* 垂直方向居中 */
  justify-content: flex-start; /* 子项从左开始排列 */
  position: relative; /* 为绝对定位提供参考 */
}

.add-button {
  margin-top: 21px;
  position: absolute; /* 绝对定位 */
  right: 0; /* 靠父容器右侧 */
  border-radius: 50%; /* 圆形按钮 */
  font-size: 28px; /* 按钮文字大小 */
  font-weight: bold; /* 按钮文字加粗 */
  color: #fff; /* 按钮文字颜色 */
  width: 40px; /* 按钮宽度 */
  height: 40px; /* 按钮高度 */
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直方向居中 */
  justify-content: center; /* 水平方向居中 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  font-family: Arial;
  transition: background-color 0.3s ease, transform 0.3s ease; /* 添加平滑过渡效果 */
}

/* 样式1：红色背景，加号不旋转 */
.join {
  background-color: red;
  transform: rotate(0deg); /* 默认不旋转 */
}

/* 样式2：黑色背景，加号旋转45度 */
.quit {
  background-color: black;
  transform: rotate(45deg); /* 旋转45度 */
}

</style>
